// 获取当前玩家信息
const currentPlayer = JSON.parse(localStorage.getItem('player'));

// 页面加载完成后初始化
$(document).ready(function() {
    if (!currentPlayer) {
        window.location.href = '/login';
        return;
    }

    loadFriendList();
    loadFriendRequests();
    
    // 定期刷新好友请求数量
    setInterval(updateFriendRequestCount, 30000);
});

// 加载好友列表
function loadFriendList() {
    $.get(`/api/friends/list/${currentPlayer.id}`)
        .done(function(friends) {
            const friendList = $('#friendList');
            friendList.empty();
            
            if (!friends || friends.length === 0) {
                friendList.append(`
                    <div class="friend-item">
                        <div class="text-center text-muted w-100">暂无好友</div>
                    </div>
                `);
                return;
            }
            
            friends.forEach(friend => {
                if (friend) {  // 添加空值检查
                    friendList.append(createFriendItem(friend));
                }
            });
        })
        .fail(function(error) {
            handleError(error, '加载好友列表失败');
        });
}

// 加载好友请求
function loadFriendRequests() {
    $.get(`/api/friends/pending/${currentPlayer.id}`)
        .done(function(requests) {
            const requestList = $('#friendRequests');
            requestList.empty();
            
            if (requests.length === 0) {
                requestList.append(`
                    <div class="friend-item">
                        <div class="text-center text-muted w-100">暂无好友请求</div>
                    </div>
                `);
                return;
            }
            
            requests.forEach(request => {
                requestList.append(createRequestItem(request));
            });
            
            // 更新好友请求数量
            updateFriendRequestCount(requests.length);
        })
        .fail(function(error) {
            showMessage('加载好友请求失败', 'error');
        });
}

// 创建好友列表项
function createFriendItem(friend) {
    return `
        <div class="friend-item">
            <div class="friend-info">
                <div class="friend-avatar">
                    <i class="fas fa-user"></i>
                </div>
                <div class="friend-name">${friend.username}</div>
            </div>
            <div class="friend-actions">
                <button class="btn btn-primary btn-friend" onclick="inviteToGame(${friend.id})">
                    <i class="fas fa-gamepad me-1"></i>邀请游戏
                </button>
                <button class="btn btn-danger btn-friend" onclick="removeFriend(${friend.id})">
                    <i class="fas fa-user-minus me-1"></i>删除好友
                </button>
            </div>
        </div>
    `;
}

// 创建好友请求项
function createRequestItem(request) {
    return `
        <div class="friend-item">
            <div class="friend-info">
                <div class="friend-avatar">
                    <i class="fas fa-user"></i>
                </div>
                <div class="friend-name">${request.player.username}</div>
            </div>
            <div class="friend-actions">
                <button class="btn btn-success btn-friend" onclick="acceptRequest(${request.id})">
                    <i class="fas fa-check me-1"></i>接受
                </button>
                <button class="btn btn-danger btn-friend" onclick="rejectRequest(${request.id})">
                    <i class="fas fa-times me-1"></i>拒绝
                </button>
            </div>
        </div>
    `;
}

// 发送好友请求
function sendFriendRequest() {
    const username = $('#friendUsername').val().trim();
    if (!username) {
        handleWarning('请输入用户名');
        return;
    }
    
    if (username === currentPlayer.username) {
        handleWarning('不能添加自己为好友');
        return;
    }
    
    $.post('/api/friends/request/byUsername', {
        username: username,
        playerId: currentPlayer.id
    })
    .done(() => {
        handleSuccess('好友请求已发送');
        $('#friendUsername').val('');
    })
    .fail(error => {
        if (error.responseJSON && error.responseJSON.message) {
            handleWarning(error.responseJSON.message);
        } else {
            handleError(error, '发送好友请求失败');
        }
    });
}

// 接受好友请求
function acceptRequest(requestId) {
    $.post(`/api/friends/accept/${requestId}`)
        .done(() => {
            handleSuccess('已接受好友请求');
            loadFriendRequests();
            loadFriendList();
        })
        .fail(error => {
            if (error.responseJSON && error.responseJSON.message) {
                handleWarning(error.responseJSON.message);
            } else {
                handleError(error, '接受好友请求失败');
            }
        });
}

// 拒绝好友请求
function rejectRequest(requestId) {
    $.ajax({
        url: `/api/friends/reject/${requestId}`,
        method: 'DELETE'
    })
    .done(() => {
        handleSuccess('已拒绝好友请求');
        loadFriendRequests();
    })
    .fail(error => handleError(error, '拒绝好友请求失败'));
}

// 删除好友
function removeFriend(friendId) {
    if (!confirm('确定要删除这个好友吗？')) {
        return;
    }
    
    $.ajax({
        url: `/api/friends/remove/${friendId}?playerId=${currentPlayer.id}`,
        method: 'DELETE'
    })
    .done(() => {
        handleSuccess('已删除好友');
        loadFriendList();
    })
    .fail(error => handleError(error, '删除好友失败'));
}

// 邀请好友加入游戏
function inviteToGame(friendId) {
    // TODO: 实现邀请好友加入游戏的功能
    showMessage('邀请功能开发中...', 'info');
}

// 更新好友请求数量
function updateFriendRequestCount(count) {
    if (typeof count !== 'number') {
        $.get(`/api/friends/pending/${currentPlayer.id}/count`)
            .done(function(response) {
                updateBadge(response);
            });
    } else {
        updateBadge(count);
    }
}

// 更新徽章显示
function updateBadge(count) {
    const badge = $('#friendRequestCount');
    if (count > 0) {
        badge.text(count).show();
    } else {
        badge.hide();
    }
}

// 显示消息提示
function showMessage(message, type = 'info') {
    // 根据消息类型设置样式
    const styles = {
        error: {
            icon: '<i class="fas fa-times-circle"></i>',
            bgClass: 'bg-danger',
            title: '错误'
        },
        success: {
            icon: '<i class="fas fa-check-circle"></i>',
            bgClass: 'bg-success',
            title: '成功'
        },
        warning: {
            icon: '<i class="fas fa-exclamation-circle"></i>',
            bgClass: 'bg-warning text-dark',
            title: '警告'
        },
        info: {
            icon: '<i class="fas fa-info-circle"></i>',
            bgClass: 'bg-info',
            title: '提示'
        }
    };

    const style = styles[type] || styles.info;

    // 创建消息元素
    const messageElement = $(`
        <div class="message-popup">
            <div class="message-content ${style.bgClass}">
                <div class="message-icon">
                    ${style.icon}
                </div>
                <div class="message-text">
                    <div class="message-title">${style.title}</div>
                    <div class="message-body">${message}</div>
                </div>
            </div>
        </div>
    `);

    // 添加样式
    const styleElement = $(`
        <style>
            .message-popup {
                position: fixed;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                z-index: 9999;
                animation: slideDown 0.3s ease-out;
            }

            .message-content {
                display: flex;
                align-items: center;
                padding: 15px 25px;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                color: white;
                min-width: 300px;
            }

            .message-icon {
                font-size: 24px;
                margin-right: 15px;
            }

            .message-text {
                flex: 1;
            }

            .message-title {
                font-weight: 600;
                margin-bottom: 2px;
            }

            .message-body {
                font-size: 0.95em;
            }

            @keyframes slideDown {
                from {
                    transform: translate(-50%, -100%);
                    opacity: 0;
                }
                to {
                    transform: translate(-50%, 0);
                    opacity: 1;
                }
            }

            @keyframes fadeOut {
                from {
                    opacity: 1;
                }
                to {
                    opacity: 0;
                }
            }

            .bg-warning {
                color: #000 !important;
            }

            .bg-warning .message-icon {
                color: #000 !important;
            }
        </style>
    `);

    // 添加到页面
    $('head').append(styleElement);
    $('body').append(messageElement);

    // 3秒后消失
    setTimeout(() => {
        messageElement.css('animation', 'fadeOut 0.3s ease-out forwards');
        setTimeout(() => {
            messageElement.remove();
            styleElement.remove();
        }, 300);
    }, 3000);
}

// 修改错误处理
function handleError(error, defaultMessage) {
    let errorMessage = defaultMessage;
    if (error.responseJSON && error.responseJSON.message) {
        errorMessage = error.responseJSON.message;
    }
    showMessage(errorMessage, 'error');
}

// 修改成功处理
function handleSuccess(message) {
    showMessage(message, 'success');
}

// 修改警告处理
function handleWarning(message) {
    showMessage(message, 'warning');
}

// 添加错误状态检查函数
function checkResponse(response) {
    if (!response.ok) {
        throw new Error(response.statusText);
    }
    return response;
} 